<?php

namespace App\Http\Controllers\Admin;

use Image;
// use Redis;
use App\Model\Cate;
use App\Model\Article;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;

class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $article = [];

        $listkey = 'LIST:ARTICLE';
        $hashkey = 'HASH:ARTICLE:';

        if (Redis::exists($listkey)) {
            $lists = Redis::lrange($listkey,0,-1);

            foreach ($lists as $k => $v) {
                $article[] = Redis::hgetall($hashkey.$v);
            }
        }else{
            $article = Article::get()->toArray();

            foreach ($article as $k => $v) {
                Redis::rpush($listkey,$v['id']);
                Redis::expire($listkey,600);
                Redis::hmset($hashkey.$v['id'],$v);
                Redis::expire($hashkey.$v['id'],600);
            }
        }

        // $article = Article::orderBy('id','asc')
        //     ->where(function($query) use($request){
        //         $art_title = $request->input('art_title');
        //         if (!empty($art_title)) {
        //             # code...
        //             $query->where('art_title','like','%'.$art_title.'%');
        //         }
        //     })->paginate($request->input('num')?$request->input('num'):5);

        $i = 1;
        return view('admin.article.list',compact('article','i'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        $cates = (new Cate())
                ->tree();

        $user = session('user')[0]->user_name;

        return view('admin.article.create',compact('cates','user'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //接收表单数据
        $info = $request->except('photo');
        // dd($info);

        $info['art_time'] = time();
        //执行添加文章操作
        $res = Article::insert($info,true);
        //判断执行结果，将状态返回至页面
        if ($res) {
            # code...
            $data = [
                'status'=>0,
                'message'=>'添加成功'
            ];
        } else {
            $data = [
                'status'=>1,
                'message'=>'添加失败'
            ];
        }
        return $data;
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $cates = (new Cate())
                ->tree();
        $article = Article::find($id);
        $user = session('user')[0]->user_name;

        return view('admin.article.edit',compact('cates','article','user'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        $info = $request->except('photo');

        $info['art_time'] = time();

        $res = Article::where('id', $id)
            ->update($info,true);
        //判断执行结果，将状态返回至页面
        if ($res) {
            $data = [
                'status' => 0,
                'message' => '修改成功'
            ];
        }else{
            $data = [
                'status' => 1,
                'message' => '修改失败'
            ];
        }
        return $data;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        $res = Article::where('id', $id)
            ->delete();

        if ($res) {
            # code...
            $data = [
                'status'=>0,
                'message'=>'删除成功'
            ];
        } else {
            $data = [
                'status'=>1,
                'message'=>'删除失败'
            ];
        }
        return $data;
    }

    public function upload(Request $request)
    {
        //
        $file = $request->file('photo');

        if (!$file->isValid()) {
            # code...
            return response()->json(['ServerNo'=>'400','ResultData'=>'无效的上传文件']);
        }

        $ext = $file->getClientOriginalExtension();

        $newName = md5(time().rand(1000,9999)).'.'.$ext;
        // dd($newName);

        $path = public_path('uploads');

        $res = Image::make($file)->resize(100,100)->save($path.'/'.$newName);

        if ($res) {
            # code...
            return response()->json(['ServerNo'=>'200','ResultData'=>$newName]);
        }else{
            return response()->json(['ServerNo'=>'400','ResultData'=>'文件上传失败']);
        }
        // if (!$file->move($path,$newName)) {
        //     # code...
        //     return response()->json(['ServerNo'=>'400','ResultData'=>'保存文件失败']);
        // }
    }
}
